import { ElMessage } from 'element-plus';
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { validateToken } from '../utils/auth-utils';
import moment from 'moment';

const Home = () => import('../views/Home.vue');
const Login = () => import('../views/Login.vue');
const Register = () => import('../views/Register.vue');
const Profile = () => import('../views/Profile.vue');
const SellerOrderManagement = () => import('../views/SellerOrderManagement.vue');
const BuyerOrderManagement = () => import('../views/BuyerOrderManagement.vue');
const Chat = () => import('../views/ChatView.vue');

// 简单路由配置
const routes: RouteRecordRaw[] = [
  // 商品详情页面
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('../views/ProductDetail.vue'),
    meta: { requiresAuth: true }
  },
  // 浏览历史页面
  {
    path: '/browse-history',
    name: 'BrowseHistory',
    component: () => import('../views/BrowseHistory.vue'),
    meta: { requiresAuth: true }
  },
  { path: '/',
    name: 'Home',
    component: Home
  },
  { path: '/chat',
    name: 'Chat',
    component: Chat,
    meta: { requiresAuth: true }
  },
  {
    path: '/announcements',
    name: 'Announcements',
    component: () => import('../views/Announcements.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta: { requiresAuth: true }
  },
  // 添加商品发布页面路由
  {
    path: '/product',
    name: 'Product',
    component: () => import('../views/Product.vue'),
    meta: { requiresAuth: true }
  },
  { path: '/admin',
    name: 'Admin', 
    component: () => import('../views/AdminHome.vue'), 
    meta: { requiresAuth: true } },

  // 管理员个人资料页面路由
  { path: '/admin/profile', 
    name: 'AdminProfile', 
    component: () => import('../views/AdminProfile.vue'), 
    meta: { requiresAuth: true } 
  },
  
  // 管理员用户管理页面路由
  { 
    path: '/admin/users',
    name: 'AdminUsers',
    component: () => import('../views/AdminUserManagement.vue'),
    meta: {
      requiresAuth: true,
      role: 'admin',
      requiresAdmin: true
    },
  },
  
  // 添加管理员用户管理页面路由
  { 
    path: '/admin/products',
    name: 'AdminProducts',
    component: () => import('../views/AdminProductManagement.vue'),
    meta: {
      requiresAuth: true,
      role: 'admin',
      requiresAdmin: true
    },
    children: [
      { path: 'users', name: 'adminUsers', component: () => import('../views/AdminUserManagement.vue') },
      { path: 'products', name: 'adminProducts', component: () => import('../views/AdminProductManagement.vue') },
    ],
  },

  // 管理员公告管理页面路由
  { 
    path: '/admin/announcements',
    name: 'AdminAnnouncements',
    component: () => import('../views/AdminAnnouncements.vue'),
    meta: {
      requiresAuth: true,
      role: 'admin',
      requiresAdmin: true
    }
  },
  // 管理员交易管理页面路由
  {
    path: '/admin/transactions',
    name: 'AdminTransactions',
    component: () => import('../views/AdminTransactionManagement.vue'),
    meta: {
      requiresAuth: true,
      role: 'admin',
      requiresAdmin: true
    }
  },
  // 卖家交易管理页面路由
  {
    path: '/seller/orders',
    name: 'SellerOrders',
    component: SellerOrderManagement,
    meta: {
      requiresAuth: true
    }
  },
  // 买家订单管理页面路由
  {
    path: '/buyer/orders',
    name: 'BuyerOrders',
    component: BuyerOrderManagement,
    meta: {
      requiresAuth: true
    }
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫：验证登录状态
router.beforeEach(async (to, _from, next) => {
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    // 检查本地存储的登录状态
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.warning('请先登录');
      next('/login');
      return;
    }

    // 验证token有效性
    const isValid = await validateToken();
    if (!isValid) {
      ElMessage.warning('登录已过期，请重新登录');
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      next('/login');
      return;
    }
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      ElMessage.warning('请先登录');
      next('/login');
      return;
    }
    const user = JSON.parse(userStr);
    if (user.role !== 1) {
      ElMessage.error('没有管理员权限');
      next('/');
      return;
    }
  }

  // 管理员角色自动跳转
  const userStr = localStorage.getItem('user');
  if (userStr) {
    const user = JSON.parse(userStr);
    // 如果是管理员且访问的是普通首页，则重定向到管理员首页
    if (user.role === 1 && to.path === '/') {
      next('/admin');
      return;
    }
  }
  
  next();
});

export default router;